/*
 * @Author: 李超越 1509572300@qq.com
 * @Date: 2024-07-31 13:54:07
 * @LastEditors: 李超越 1509572300@qq.com
 * @LastEditTime: 2024-07-31 14:33:01
 * @FilePath: /my_git/lesson26_shm/Fifp.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#ifndef __FIFO_HPP__
#define __FIFO_HPP__



#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
using namespace std;


#define Mode 0666
#define Path "fifo"


class Fifo
{
public:
    Fifo(const string &path=Path):_path(path)
    {
        umask(0);
        int n=mkfifo(_path.c_str(),Mode);
        if(n==0)
        {
            cout<<"mififo success"<<endl;
        }
        else
        {
            cerr<<"mkfifo failed,errno:"<<errno<<",errstring:"<<strerror(errno)<<endl;
        }
    }
    ~Fifo()
    {
        int n=unlink(_path.c_str());
        if(n==0)
        {
            cout<<"remove fifo file"<<_path<<"success"<<endl;
        }
        else
        {
            cerr<<"remove fifo,errno"<<errno<<"errstring"<<strerror(errno)<<endl;
        }
    }
private:
    string _path;//文件路径+文件名
};

class Sync
{
public:
    Sync():rfd(-1),wfd(-1)
    {}

    void OpenRead()
    {
        rfd=open(Path,O_RDONLY);
        if(rfd<0)
        {
            exit(1);
        }
    }

    void OpenWrite()
    {
        wfd=open(Path,O_WRONLY);
        if(wfd<0)
        {
            exit(1);
        }
    }

    bool Wait()
    {
        uint64_t c=0;
        ssize_t n=read(rfd,&c,sizeof(uint64_t));
        if(n==sizeof(uint64_t))
        {
            return true;
        }
        return false;
    }

    bool WakeUp()
    {
        uint64_t c=0;
        ssize_t n=write(wfd,&c,sizeof(c));
        if(n==sizeof(uint64_t))
        {
            return true;
        }
        return false;
    }

    ~Sync()
    {}

private:
    int rfd;
    int wfd;
};


#endif